package com.bootdo.acitvity.DDD.domain.event;

import com.bootdo.acitvity.DDD.domain.CenterBatch;
import com.bootdo.acitvity.DDD.domain.entity.ChannelLockedStock;
import com.bootdo.acitvity.DDD.domain.entity.ShareStock;
import com.bootdo.acitvity.DDD.domain.entity.Stock;

public class StockLockUpdateStrategy implements StockUpdateStrategy {

    @Override
    public void updateStock(CenterBatch batch, Stock stockChange) {
        if (!(stockChange instanceof ChannelLockedStock)) {
            throw new IllegalArgumentException();
        }
        ChannelLockedStock dto = (ChannelLockedStock) stockChange;
        ShareStock shareStockTobeUpdated = batch.getShareStock();

        // 没操作之前的锁定库存
        ChannelLockedStock lockedStock = batch.getLockedStock(dto.getChannelId());
        // 新增还是减少
        boolean isAdd = lockedStock.compareTo(dto) <= 0;

        Long num = 0L;
        if (isAdd) {
            // 减少共享库存
            ChannelLockedStock reduce = dto.reduce(lockedStock);
            num = reduce.getStockAmount();
            ShareStock shareStockReduced = shareStockTobeUpdated.reduce(reduce);
            batch.setShareStock(shareStockReduced);
            batch.updateLockedStock(dto);
        } else {
            // 增加共享库存
            ChannelLockedStock add = lockedStock.reduce(dto);
            num = add.getStockAmount();
            ShareStock shareStockReduced = shareStockTobeUpdated.add(add);
            batch.setShareStock(shareStockReduced);
            batch.updateLockedStock(dto);
        }

    }
}
